<?php
/*
YHM (Your Hosting Manager) - Copyright 2010 All Rights Reserved. - YHM Group
Released under the Simplified BSD Licence.

Website: http://yhm.co.uk
Licence: http://yhm.co.uk/about/#licence

file: install/index.php
author: Kieran D. (Polarbear541)
*/

require_once("./resources/functions.php");
error_reporting(0);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
	<meta name="author" content="Kieran Dunbar (Polarbear541)" />
	<link rel="stylesheet" type="text/css" href="./style.css" media="screen" />
	<title>YHM Preview1 Install</title>
</head>
<body>

   <div id="wrapper">

		<div id="header">
			<img src="./images/logo.png" alt="YHM Installer" />		
		</div>
		
		<?php
		$action = $_POST['action'];	

		if(file_exists('lock'))
		{
			$action = "locked";
		}
		
		switch ($action)
		{
			case 'licence':			
			echo "<div id='navigation'>Overview - <b>Licence</b> - Requirements - Database Details - Settings - Admin Details - Finish</div>";			
			echo "<div id='content'>";
			licence();
			break;		

			case 'requirements':			
			echo "<div id='navigation'>Overview - Licence - <b>Requirements</b> - Database Details - Settings - Admin Details - Finish</div>";			
			echo "<div id='content'>";
			requirements();
			break;			
			
			case 'database':			
			echo "<div id='navigation'>Overview - Licence - Requirements - <b>Database Details</b> - Settings - Admin Details - Finish</div>";			
			echo "<div id='content'>";
			database();
			break;		
			
			case 'do_database':			
			echo "<div id='navigation'>Overview - Licence - Requirements - <b>Database Details</b> - Settings - Admin Details - Finish</div>";			
			echo "<div id='content'>";
			do_database();
			break;
			
			case 'settings':			
			echo "<div id='navigation'>Overview - Licence - Requirements - Database Details - <b>Settings</b> - Admin Details - Finish</div>";			
			echo "<div id='content'>";
			settings();
			break;

			case 'do_settings':			
			echo "<div id='navigation'>Overview - Licence - Requirements - Database Details - <b>Settings</b> - Admin Details - Finish</div>";			
			echo "<div id='content'>";
			do_settings();
			break;
			
			case 'admin':			
			echo "<div id='navigation'>Overview - Licence - Requirements - Database Details - Settings - <b>Admin Details</b> - Finish</div>";			
			echo "<div id='content'>";
			admin();
			break;
			
			case 'do_admin':			
			echo "<div id='navigation'>Overview - Licence - Requirements - Database Details - Settings - <b>Admin Details</b> - Finish</div>";			
			echo "<div id='content'>";
			do_admin();
			break;
			
			case 'finish':			
			echo "<div id='navigation'>Overview - Licence - Requirements - Database Details - Settings - Admin Details - <b>Finish</b></div>";			
			echo "<div id='content'>";
			finish();
			break;	
			
			case 'locked':
			echo "<div id='navigation'><b>Overview</b> - Licence - Requirements - Database Details - Settings - Admin Details - Finish</div>";			
			echo "<div id='content'>";
			locked();
			break;
			
			default:			
			echo "<div id='navigation'><b>Overview</b> - Licence - Requirements - Database Details - Settings - Admin Details - Finish</div>";			
			echo "<div id='content'>";
			overview();
			break;
		}
		
		function overview()
		{
			$nextpage = "licence";
			
			//Welcome Text
			echo "<p>Welcome to your YHM installation. This wizard will guide you through the licence, database configuration and your admin account creation.
			<br /><br />We hope you enjoy this software and remember, if you ever have any problems with it, feel free to submit it to the
			<a href='http://yhm.co.uk/forums'>General Support Board</a>. <br />Also, as this is a beta release, please submit any bugs
			you find to the <a href='http://dev.yhm.co.uk/projects/yhm/issues'>YHM Development Site</a>.<br /><br />";	
			
			//Installation Overview
			echo "Below is an outline of what will happen during this installation:
			<ul>
			<li>YHM Licence</li>
			<li>Requirements Check</li>
			<li>Configuration of the database and creation of database tables</li>
			<li>Creation of an administrator account to manage the ideas</li>
			</ul>
			After each step has successfully been completed, click Next to move on to the next step.";		
			
			//Next Button
			echo "<br />Click 'Next' to view the YHM Licence and start the install.</p><br />
			<form method='POST' action='./index.php'>
			<input type='hidden' name='action' value='$nextpage' />
			<br /><input type='submit' value='Next' />
			</form>";
		}
		
		function licence()
		{
			$nextpage = "requirements";		
			
			//Licence Intro
			echo "YHM is released under the Simplified BSD Licence (shown below):<br />";
			
			//Licence Text
			echo "<br /><div id='licence'><pre>";
			echo "Copyright 2010 YHM. All rights reserved.
			
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided with
the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,  STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of YHM.";
			echo "</pre></div><br />";
			
			//Next Button
			echo "By clicking 'Next' you agree to the terms stated in the licence above.<br />
			<form method='POST' action='./index.php'>
			<input type='hidden' name='action' value='$nextpage' />
			<br /><input type='submit' value='Next' />
			</form>";
		}				
		
		function requirements()
		{
			$nextpage = "database";

			if (!file_exists("../includes/config.php"))
			{
				error("config.php does not exist! Please rename config.php.default to config.php.");
				$err = 1;
			}
			if (!is_writable("../includes/config.php"))
			{
				error("config.php is not writable! Please chmod config.php to 666.");
				$err = 1;
			}
			
			if ($err == 1)
			{
				//Re-Check Button
				echo "Click 'Check Again' to try again.<br />
				<form method='POST' action='./index.php'>
				<input type='hidden' name='action' value='requirements' />
				<br /><input type='submit' value='Check Again' />
				</form>";
			}
			else
			{
				//Next Button
				echo "No Problems Found!<br />Click 'Next' to continue.<br />
				<form method='POST' action='./index.php'>
				<input type='hidden' name='action' value='$nextpage' />
				<br /><input type='submit' value='Next' />
				</form>";
			}
		}
		
		function database()		
		{			
			$nextpage = "do_database";						
			
			//DB Intro and Fields	
			echo "<form method='POST' action='./index.php'>";
			echo "Enter your database hostname, username, password and database name below to continue YHM's installation.<br /><br />";			
			echo "Hostname: <br /><input type='text' name='hostname' value='localhost' /><br />";	
			echo "Username: <br /><input type='text' name='username' /><br />";
			echo "Password: <br /><input type='password' name='password' /><br />";
			echo "Database: <br /><input type='text' name='database' /><br />";
			echo "Table Prefix: <br /><input type='text' name='table_prefix' value='yhm_' /><br /><br />";
			
			//Next Button
			echo "Click 'Next' to continue.<br />
			<input type='hidden' name='action' value='$nextpage' />
			<br /><input type='submit' value='Next' />
			</form>";
		}
		
		function do_database()
		{
			$nextpage="settings";
			
			//Init Variables
			$hostname = $_POST['hostname'];
			$username = $_POST['username'];
			$password = $_POST['password'];
			$database = $_POST['database'];
			$prefix = $_POST['table_prefix'];
			
			if (empty($hostname)) //If hostname empty set message and redirect
			{
				error("You must provide a hostname!");
				database();
			}
			
			elseif (empty($username)) //If username empty set message and redirect
			{
				error("You must provide a username!");
				database();
			}
			
			elseif (empty($database)) //If database empty set message and redirect
			{
				error("You must provide a database name!");
				database();
			}
			
			else
			{
				$connect = mysql_connect("$hostname", "$username", "$password");
				$select = mysql_select_db("$database");
				
				if (!$connect && !$select)
				{	
					error("Cannot connect to host or database");
					database();
				}
				
				elseif (!$connect)
				{
					error("Cannot connect to host!");
					database();
				}
				
				elseif (!$select)
				{
					error("Cannot connect to database!");
					database();
				}
				
				else
				{
					//Echo stuff and run queries to create basic tables
					echo "Connected Successfully.<br />Running Queries...<br /><br />";
					include ("./resources/tables.php");
					
					echo "Creating table ".$prefix."announcements...<br />";
					$result1 = mysql_query($create1) or error("Failed to create table ".$prefix."announcements - " . mysql_error());
					
					echo "Creating table ".$prefix."countries...<br />";
					$result2 = mysql_query($create2) or error("Failed to add countries table into database - " . mysql_error());

					echo "Creating table ".$prefix."knowledgebase...<br />";
					$result2 = mysql_query($create3) or error("Failed to add knowledgebase table into database - " . mysql_error());
					
					echo "Creating table ".$prefix."packagesgroups...<br />";
					$result3 = mysql_query($create4) or error("Failed to add packagegroups table into database - " . mysql_error());
					
					echo "Creating table ".$prefix."packages...<br />";
					$result4 = mysql_query($create5) or error("Failed to add packages table into database - " . mysql_error());
					
					echo "Creating table ".$prefix."servers...<br />";
					$result5 = mysql_query($create6) or error("Failed to add servers table into database - " . mysql_error());
					
					echo "Creating table ".$prefix."settings...<br />";
					$result6 = mysql_query($create7) or error("Failed to add settings table into database - " . mysql_error());
					
					echo "Creating table ".$prefix."subdomains...<br />";
					$result7 = mysql_query($create8) or error("Failed to add subdomains table into database - " . mysql_error());
					
					echo "Creating table ".$prefix."tickets...<br />";
					$result8 = mysql_query($create9) or error("Failed to add tickets table into database - " . mysql_error());
					
					echo "Creating table ".$prefix."users...<br />";
					$result9 = mysql_query($create10) or error("Failed to add users table into database - " . mysql_error());
					
					echo "Creating configuration file...<br /><br />";
					
					//Create Config
					$config = "<?php
/*
YHM (Your Hosting Manager) - Copyright 2010 All Rights Reserved. - YHM Group
Released under the Simplified BSD Licence.

Website: http://yhm.co.uk
Licence: http://yhm.co.uk/about/#licence

file: includes/config.php
*/

\$db_host = '$hostname';
\$db_user = '$username';
\$db_pass = '$password';
\$db_name = '$database';
\$prefix = '$prefix';

?>";
					$file = fopen('../includes/config.php', 'w');
					fwrite($file, $config);
					fclose($file);					
					echo "Done.<br />";
					
					
					//Next Button
					echo "Click 'Next' to continue.<br />
					<form method='POST' action='./index.php'>
					<input type='hidden' name='action' value='$nextpage' />
					<br /><input type='submit' value='Next' /></form>";
				}
			}
		}
		
		function settings()
		{
			$nextpage = "do_settings";
			sql_connect();
			
			if ($_SERVER['HTTPS'] != NULL)
			{
				$s = "s";
			}
			
			$url = 'http'. $s .'://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
			$url = dirname(dirname($url));
			
			echo "Please fill in the following settings below:<br /><br />";
			
			//title
			$query = mysql_query("SELECT * FROM ".TABLE_PREFIX."settings WHERE id='1'");
			$row = mysql_fetch_array($query);
			echo "<b>{$row['acpname']}</b>";
			echo "<p>{$row['desc']}</p>";
			echo "<input type='text' value='YHM' name='{$row['name']}' /><br /><br />";

			//url
			$query = mysql_query("SELECT * FROM ".TABLE_PREFIX."settings WHERE id='2'");
			$row = mysql_fetch_array($query);
			echo "<b>{$row['acpname']}</b>";
			echo "<p>{$row['desc']}</p>";
			echo "<input type='text' value='$url' size='30' name='{$row['name']}' /><br /><br />";

			//sendmail
			$query = mysql_query("SELECT * FROM ".TABLE_PREFIX."settings WHERE id='3'");
			$row = mysql_fetch_array($query);
			echo "<b>{$row['acpname']}</b>";
			echo "<p>{$row['desc']}</p>";
			echo "<input type='text' value='yhm@{$_SERVER['HTTP_HOST']}' size='30' name='{$row['name']}' /><br /><br />";
		
			//Next Button
			echo "Click 'Next' to continue.
			<form method='POST' action='./index.php'>
			<input type='hidden' name='action' value='$nextpage' />
			<input type='submit' value='Next' /></form>";
		}
		
		function do_settings()
		{
			$nextpage = "admin";
			
			echo "Inserting Settings...<br />";
			
			//title
			mysql_query("UPDATE ".TABLE_PREFIX."settings SET value='{$_POST['title']}' WHERE id='1'") or error("There was an error updating the settings! Please try again.");
			//url
			mysql_query("UPDATE ".TABLE_PREFIX."settings SET value='{$_POST['url']}' WHERE id='2'") or error("There was an error updating the settings! Please try again.");
			//sendmail
			mysql_query("UPDATE ".TABLE_PREFIX."settings SET value='{$_POST['sendmail']}' WHERE id='3'") or error("There was an error updating the settings! Please try again.");
			
			echo "Done.<br /><br />";
			
			//Next Button
			echo "Click 'Next' to continue.
			<form method='POST' action='./index.php'>
			<input type='hidden' name='action' value='$nextpage' />
			<input type='submit' value='Next' /></form>";
		}
		
		function admin()
		{
			$nextpage = "do_admin";
			
			//DB Intro and Fields	
			echo "<form method='POST' action='./index.php'>";
			echo "Enter your wanted admin username, password and email below to continue YHM's installation.<br /><br />";			
			echo "Username: <br /><input type='text' name='username' /><br /><br />";	
			echo "Password: <br /><input type='password' name='password' /><br /><br />";
			echo "Email: <br /><input type='text' name='email' /><br /><br />";
			
			//Next Button
			echo "Click 'Next' to continue.<br />
			<input type='hidden' name='action' value='$nextpage' />
			<br /><input type='submit' value='Next' /></form>";
		}
		
		function do_admin()
		{
			$nextpage = "finish";
			sql_connect();
			
			$username = mysql_real_escape_string($_POST['username']);
			$password = mysql_real_escape_string($_POST['password']);
			$email = mysql_real_escape_string($_POST['email']);
			
			if (empty($username) || empty($password) || empty($email))
			{
				error("Please fill in all the fields!");
			}
			
			else
			{
				//Encrypt password with existing salt
				$salt = random_str(10);
				$epassword = md5($salt.md5($password.$salt));
				$epassword = md5($epassword);
			
				$addadmin = mysql_query("INSERT INTO ".TABLE_PREFIX."users(id, username, password, salt, email, gid) VALUES (NULL, '$username', '$epassword', '$salt', '$email', '1')");
			
				if (!$addadmin)
				{
					error("Failed to create administrator's account - " . mysql_error());
				}
			
				else
				{
					echo "Creating administrator's account...<br /><br />";
					echo "Done.<br /><br />";
					
					//Next Button
					echo "Click 'Finish' to complete YHM's installation.<br /><br />
					<form method='POST' action='./index.php'>
					<input type='hidden' name='action' value='$nextpage' />
					<input type='submit' value='Finish' /></form>";
				}
			}
		}
		
		function finish()
		{
			$lock = @fopen('./lock', 'w');
			$written = @fwrite($lock, 'locked');
			@fclose($lock);
		
			echo "<h2>Congratulations! YHM has been installed successfully!</h2>";
			echo "Your installer has also been locked to prevent unauthorised reinstalls or updates.<br />";
			echo "To start using YHM, click <a href='../index.php'>here</a> and you will be taken directly to the homepage where you can login to your admin account.<br /><br />";
			echo "Remember, if you have any problems with our software, please make a support request over at our <a href='http://yhm.co.uk/forums'>Support Forums</a>.<br />";
			echo "If you happen to encounter any bugs with YHM, (which may be likely as this is a preview release) please report them onto the <a href='http://dev.yhm.co.uk/projects/yhm/issues'>YHM Development Site</a>.";
		}
		
		function locked()
		{
			error("The installer is currently locked, and therefore cannot continue. Please remove the 'lock' file to continue and refresh.");
			echo "If this problem continues, please feel free to make a support request over at our <a href='http://yhm.co.uk/forums'>Support Forums</a>.";
		}
		?>		
		</div>		
		 <div id="footer">
			&copy; <?php
			$copyYear = 2010;
			$curYear = date('Y');
			echo $copyYear . (($copyYear != $curYear) ? ' - ' . $curYear : ''); ?>
			<a href="http://yhm.co.uk/">YHM</a>
	     </div>		
</div>
</body>
</html>